﻿#region License

// Another free, open solution by someone who gets it.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;

using FluentValidation;
using FluentValidation.Results;

namespace Patterns.Validation
{
	/// <summary>
	/// 	Defines a validator that can be configured at runtime.
	/// </summary>
	/// <typeparam name = "T">The type of object to validate.</typeparam>
	public class LambdaValidator<T> : AbstractValidator<T>
	{
		private readonly string _message;
		private readonly string _target;
		private readonly Predicate<T> _validator;

		/// <summary>
		/// 	Initializes a new instance of the <see cref = "LambdaValidator{T}" /> class.
		/// </summary>
		/// <param name = "validator">The validator.</param>
		/// <param name = "target">The target.</param>
		/// <param name = "message">The message.</param>
		public LambdaValidator(Predicate<T> validator, string target = null, string message = null)
		{
			_validator = validator;
			_target = target ?? string.Empty;
			_message = message ?? string.Empty;
		}

		public override ValidationResult Validate(T instance)
		{
			return _validator(instance)
			       	? new ValidationResult()
			       	: new ValidationResult(new[] { new ValidationFailure(_target, _message) });
		}

		public override ValidationResult Validate(ValidationContext<T> context)
		{
			return Validate(context.InstanceToValidate);
		}
	}
}